package com.cfwx.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cfwx.net.MyServer;

public class ProcessUtil {
	
	/** 日志服务对象. */
	static final Logger LOGGER = LoggerFactory.getLogger(ProcessUtil.class);

	/**
	 * 获取运行指定类的进程的pid,在一台设备上运行多个实例，无法区分.
	 * 
	 * @param name
	 *            如果类打包在jar文件中，则传入jar文件名
	 *            如果类未打包成jar，则传入带完整包路径的类名称，使用xx类.class.getName()方法获取
	 * 
	 * @return String 如果找到则返回PID，否则返回空字符串.
	 */
	public static String getpid(String name) {
		String pid = "";

		Process p;
		BufferedReader br = null;
		try {
			p = Runtime.getRuntime().exec("jps -ml");
			InputStream in = p.getInputStream();
			InputStreamReader reader = new InputStreamReader(in, "UTF-8");
			br = new BufferedReader(reader);
			String s = null;
			StringBuffer sb = new StringBuffer("");
			while ((s = br.readLine()) != null) {
				LOGGER.debug(s);
				// s eg: 5412 com.cfwx.multichannel.userinterface.run.Main 5
				// 4528 d:\channelNew\middle\middle.jar 5
				String[] fileds = s.split(" ");
				if (fileds.length > 1) {
					String t = fileds[1];
					if (name.endsWith(".jar")) {
					   if (fileds[1].endsWith(name)) {
							pid = fileds[0];
							break;						   
					   }
					} else {
						if (fileds[1].equals(name)) {
							pid = fileds[0];
							break;
						}
					}
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOGGER.error(e.getMessage());
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					LOGGER.error(e.getMessage());
				}
		}

		return pid;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(getpid(MyServer.class.getName()));

	}

}
